#include "scene.h"
#include <rmxftmpl.h>

/**
 * Konstruktor domyslny
 */
Scene::Scene()
{
	rootNode = new SceneNode(NULL, std::string("root"));
}

/**
 * Destruktor
 */
Scene::~Scene()
{
	delete rootNode;
}

/**
 * Renderuje scene
 */
void Scene::drawAll()
{
	rootNode->draw();
}

/**
 * Laduje scene z danych zasobu
 */
bool Scene::loadFromResourceData(const void* data, unsigned dataSize)
{
	LPD3DXFILE xofFile = NULL;
	ID3DXFileEnumObject* xofFileEnum = NULL;
	LPD3DXFILEDATA xofFileData = NULL;
	SIZE_T childCount = NULL;
	D3DXF_FILELOADMEMORY xofLoadMemory;
	xofLoadMemory.lpMemory = data;
	xofLoadMemory.dSize = dataSize;

	// otworz plik directx
	if(FAILED(D3DXFileCreate(&xofFile)))
		return false;
	if(FAILED(xofFile->RegisterTemplates((LPCVOID)D3DRM_XTEMPLATES,
			D3DRM_XTEMPLATE_BYTES)))
		return false;
	if(FAILED(xofFile->CreateEnumObject(&xofLoadMemory,
			D3DXF_FILELOAD_FROMMEMORY, &xofFileEnum)))
		return false;

	// wczytaj podwezly
	if(FAILED(xofFileEnum->GetChildren(&childCount)))
	{
		xofFileEnum->Release();
		xofFile->Release();
		return false;
	}
	for(SIZE_T child = 0; child < childCount; child++)
	{
		if(FAILED(xofFileEnum->GetChild(child, &xofFileData)))
			continue;

		SceneNode* node = new SceneNode(rootNode);
		if(!node->loadFromXof(xofFileData))
		{
			delete node;
		}
		else
		{
			rootNode->addSubNode(node);
		}
		xofFileData->Release();
		xofFileData = NULL;
	}

	// koniec
	xofFileEnum->Release();
	xofFile->Release();
	return true;
}
